"""
Command-line interface for the Structural Text Analyzer.
"""

import argparse
import sys
import os
from pathlib import Path

from .analyzer import StructuralTextAnalyzer
from .config import ConfigManager

def create_parser():
    """Create command-line argument parser."""
    
    parser = argparse.ArgumentParser(
        description="Automated Structural Information Extraction from Text",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""Examples:
  # Analyze a computational log file
  python -m structural_analyzer solver_debug.log --type computational_log
  
  # Analyze an academic paper with custom settings
  python -m structural_analyzer paper.txt --type academic_paper --output reports/
  
  # Analyze with custom configuration
  python -m structural_analyzer data.txt --no-plots --format json
  
  # Quick analysis summary only
  python -m structural_analyzer log.txt --summary-only
        """
    )
    
    # Required arguments
    parser.add_argument(
        'input_file',
        help='Input text file to analyze'
    )
    
    # Optional arguments
    parser.add_argument(
        '--type', '-t',
        choices=['computational_log', 'academic_paper', 'social_text', 'default'],
        default='default',
        help='Text type for pre-configured analysis settings (default: default)'
    )
    
    parser.add_argument(
        '--output', '-o',
        default='output',
        help='Output directory for results (default: output)'
    )
    
    parser.add_argument(
        '--name', '-n',
        help='Analysis name (used for output filenames)'
    )
    
    parser.add_argument(
        '--format', '-f',
        choices=['markdown', 'json', 'txt'],
        default='markdown',
        help='Report format (default: markdown)'
    )
    
    parser.add_argument(
        '--text-descriptions',
        action='store_true', 
        default=True,
        help='Generate text-based analysis descriptions (default: enabled)'
    )
    
    parser.add_argument(
        '--mcp-server',
        action='store_true',
        help='Run as MCP (Model Context Protocol) server'
    )
    
    parser.add_argument(
        '--summary-only',
        action='store_true',
        help='Only generate summary, skip detailed report and visualizations'
    )
    
    parser.add_argument(
        '--include-raw',
        action='store_true',
        help='Include raw data in report'
    )
    
    # Configuration overrides
    parser.add_argument(
        '--max-file-size',
        type=int,
        help='Maximum file size in MB (default: 100)'
    )
    
    parser.add_argument(
        '--min-sequence-length',
        type=int,
        help='Minimum sequence length for trend analysis (default: 3)'
    )
    
    parser.add_argument(
        '--large-number-threshold',
        type=float,
        help='Threshold for large number detection (default: 1e10)'
    )
    
    parser.add_argument(
        '--encoding',
        default='utf-8',
        help='File encoding (default: utf-8)'
    )
    
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='Enable verbose output'
    )
    
    parser.add_argument(
        '--version',
        action='version',
        version='Structural Text Analyzer 1.0'
    )
    
    return parser

def main():
    """Main CLI entry point."""
    
    parser = create_parser()
    args = parser.parse_args()
    
    # Handle MCP server mode
    if args.mcp_server:
        print("Starting MCP Server for Structural Text Analyzer...")
        from .mcp_server import run_mcp_server
        import asyncio
        try:
            asyncio.run(run_mcp_server())
        except ImportError:
            print("Error: MCP library not found. Install with: pip install mcp")
            sys.exit(1)
        return
    
    # Validate input file
    if not os.path.exists(args.input_file):
        print(f"Error: Input file '{args.input_file}' not found.")
        sys.exit(1)
        
    # Create configuration
    config_kwargs = {
        'output_format': args.format,
        'generate_plots': False,  # Always disabled - use text descriptions
        'generate_text_descriptions': args.text_descriptions,
        'include_raw_data': args.include_raw,
        'encoding': args.encoding
    }
    
    # Add configuration overrides if provided
    if args.max_file_size is not None:
        config_kwargs['max_file_size_mb'] = args.max_file_size
        
    if args.min_sequence_length is not None:
        config_kwargs['min_sequence_length'] = args.min_sequence_length
        
    if args.large_number_threshold is not None:
        config_kwargs['large_number_threshold'] = args.large_number_threshold
        
    # Create analyzer
    if args.type != 'default':
        analyzer = StructuralTextAnalyzer.from_text_type(args.type, args.output)
        # Apply config overrides
        for key, value in config_kwargs.items():
            setattr(analyzer.config, key, value)
    else:
        analyzer = StructuralTextAnalyzer.from_custom_config(args.output, **config_kwargs)
        
    try:
        # Create output directory
        os.makedirs(args.output, exist_ok=True)
        
        print(f"Structural Text Analyzer v1.0")
        print(f"Analysis type: {args.type}")
        print(f"Output directory: {args.output}")
        print(f"Report format: {args.format}")
        print("-" * 50)
        
        if args.summary_only:
            # Quick summary analysis
            print("Running summary analysis...")
            analyzer.analyze_file(args.input_file, args.name)
            analyzer.print_summary()
            
        else:
            # Complete analysis
            outputs = analyzer.run_complete_analysis(args.input_file, args.name)
            
            print("\nGenerated outputs:")
            for output_type, path in outputs.items():
                if isinstance(path, list):
                    print(f"  {output_type}: {len(path)} files")
                    if args.verbose:
                        for file_path in path:
                            print(f"    - {file_path}")
                else:
                    print(f"  {output_type}: {path}")
                    
        print(f"\nAnalysis completed successfully!")
        
    except Exception as e:
        print(f"Error during analysis: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)

if __name__ == '__main__':
    main()
